package com.tdma.g12.sql;



import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class ConnectionStatusHelper extends SQLiteOpenHelper
{
	//Estructura
	static final String dbName = "ConnectionStatus";
	static final String ConnectionStatusTable = "ConnectionStatus";
	static final String colID = "_ID";
	static final String colFecha = "fecha";
	static final String colEstado ="estado";
	public ConnectionStatusHelper(Context context)
	{
		super(context, dbName, null, 1);
		// TODO Auto-generated constructor stub
	}
	
	//Sentencias SQL 
	//crear tabla de Conexiones
    String sqlCreate = "CREATE TABLE ConnectionStatus " +
                       "(_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                       " fecha DATE, " +
                       " estado INTEGER )";
	
	@Override
	public void onCreate(SQLiteDatabase db)
	{
		db.execSQL(sqlCreate);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2)
	{
		db.execSQL("DROP TABLE IF EXISTS " + ConnectionStatusTable);
		onCreate(db);
	}
	
	public void registrarEstado(int estado){
		SQLiteDatabase db = this.getWritableDatabase();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Date date = new Date();
		ContentValues cv = new ContentValues();
		cv.put(colEstado, estado);
		cv.put(colFecha, dateFormat.format(date));
		db.insert(ConnectionStatusTable, null, cv);
		db.close();	
	}
	
	public Cursor getHistorial()
	{
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cur = db.rawQuery(" SELECT * FROM " + ConnectionStatusTable,null);
		return cur;
	}
	
	public Cursor getLast(){
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cur = db.rawQuery(" SELECT estado FROM " + ConnectionStatusTable + " ORDER BY fecha DESC LIMIT 1",null);
		return cur;
		
	}

}
